import 'dart:async';
import 'dart:ui';

import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_getx/app/config/constant.dart';
import 'package:flutter_getx/core/utils/device_utils.dart';
import 'package:flutter_getx/res/colors/colors.dart';
import 'package:flutter_getx/res/colors/colors_dark.dart';
import 'package:flutter_getx/res/dimens/dimens.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:rxdart/rxdart.dart';

extension ThemeModeExtension on ThemeMode {
  String get value => <String>['System', 'Light', 'Dark'][index];
}

class ThemeControl extends GetxController{

  static final ThemeControl to = Get.find();

  void setTheme(ThemeMode _themeMode) {
    Get.changeThemeMode(_themeMode);
    SpUtil.putString(Constant.theme, _themeMode.value);
    //必须延时才会完全生效
    Future.delayed(const Duration(milliseconds: 250), () {
      Get.forceAppUpdate();
    });
  }

  void switchTheme(){
    ThemeMode _themeMode = Get.isDarkMode ? ThemeMode.light : ThemeMode.dark;
    setTheme(_themeMode);
  }

  ThemeMode getThemeMode() {
    final String theme = SpUtil.getString(Constant.theme) ?? '';
    switch (theme) {
      case 'Dark':
        return ThemeMode.dark;
      case 'Light':
        return ThemeMode.light;
      default:
        return ThemeMode.system;
    }
  }

  ThemeData getTheme([bool isDark = false]) {
    Brightness brightness = isDark ? Brightness.dark : Brightness.light;

    return ThemeData(
      errorColor: isDark ? colorErrorDark : colorError,
      brightness: brightness,
      primaryColor: isDark ? colorMainDark : colorMain,
      accentColor: isDark ? secondaryVariantDark : secondaryVariant,
      backgroundColor: isDark ? colorBgDark : colorBg,
      // Tab指示器颜色
      indicatorColor: isDark ? colorMainDark : colorMain,
      // 页面背景色
      scaffoldBackgroundColor: isDark ? colorBgDark : colorBg,
      // 主要用于Material背景色
      canvasColor: isDark ? colorBgDark : colorBg,
      dividerColor: isDark ? colorLineDark : colorLine,
      // 文字选择色（输入框选择文字等）
      // textSelectionColor: Colours.app_main.withAlpha(70),
      // textSelectionHandleColor: Colours.app_main,
      // 稳定版：1.23 变更(https://flutter.dev/docs/release/breaking-changes/text-selection-theme)
      textSelectionTheme: TextSelectionThemeData(
        selectionColor: isDark ? colorMainDark.withAlpha(70) : colorMain.withAlpha(70),
        selectionHandleColor: isDark ? colorMainDark : colorMain,
        cursorColor: isDark ? colorMainDark : colorMain,
      ),
      textTheme: TextTheme(
        // TextField输入文字颜色
        subtitle1: TextStyle(color: isDark ? colorTextDark : colorText, fontSize: Sp.sp16),
        // Text文字样式
        subtitle2: TextStyle(color: isDark ? colorTextDark : colorText, fontSize: Sp.sp14),
        bodyText2: TextStyle(color: isDark ? colorTextDark : colorTextWhite, fontSize: Sp.sp14),
      ),
      inputDecorationTheme: InputDecorationTheme(
        hintStyle: TextStyle(color: isDark ? colorTextHintDark : colorTextHint, fontSize: Sp.sp14),
      ),
      appBarTheme: AppBarTheme(
        elevation: 0.0,
        color: isDark ? colorBgDark : colorBg,
        brightness: brightness,
        systemOverlayStyle: SystemUiOverlayStyle(statusBarBrightness: brightness),
      ),
      dividerTheme: DividerThemeData(
          color: isDark ? colorLineDark : colorLine,
          space: 0.6,
          thickness: 0.6),
      cupertinoOverrideTheme: CupertinoThemeData(
        brightness: brightness,
      ),
      pageTransitionsTheme: NoTransitionsOnWeb(),
      visualDensity: VisualDensity.standard, // https://github.com/flutter/flutter/issues/77142
    );
  }


  StreamSubscription? _subscription;

  /// 设置NavigationBar样式，使得导航栏颜色与深色模式的设置相符。
  void setSystemNavigationBar(ThemeMode mode) {
    /// 主题切换动画（AnimatedTheme）时间为200毫秒，延时设置导航栏颜色，这样过渡相对自然。
    _subscription?.cancel();
    _subscription = Stream.value(1).delay(const Duration(milliseconds: 200)).listen((_) {
      bool _isDark = false;
      if (mode == ThemeMode.dark || (mode == ThemeMode.system && window.platformBrightness == Brightness.dark)) {
        _isDark = true;
      }
      setSystemBarStyle(isDark: _isDark);
    });
  }

  /// 设置StatusBar、NavigationBar样式。(仅针对安卓)
  /// 本项目在android MainActivity中已设置，不需要覆盖设置。
  void setSystemBarStyle({bool? isDark}) {
    if (Device.isAndroid) {

      final bool _isDark = isDark ?? window.platformBrightness == Brightness.dark;
      //debugPrint('isDark: $_isDark');
      final SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
        /// 透明状态栏
        statusBarColor: Colors.transparent,
        systemNavigationBarColor: colorBg,
        systemNavigationBarIconBrightness: _isDark ? Brightness.light : Brightness.dark,
      );
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
  }
}

/// https://medium.com/flutter/improving-perceived-performance-with-image-placeholders-precaching-and-disabled-navigation-6b3601087a2b
/// 对于Web应用程序，为了提高性能，可以禁用页面过渡动画。
class NoTransitionsOnWeb extends PageTransitionsTheme {
  @override
  Widget buildTransitions<T>(
      route,
      context,
      animation,
      secondaryAnimation,
      child,
      ) {
    if (kIsWeb) {
      return child;
    }
    return super.buildTransitions(
      route,
      context,
      animation,
      secondaryAnimation,
      child,
    );
  }
}